package net.takela.auth.login;

import net.takela.auth.login.filter.AuthTokenFilter;
import net.takela.auth.token.token.AuthTokenManager;
import net.takela.auth.token.token.AuthTokenProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

@Configuration
public class AuthTokenAutoConfig {
    //auth token的配置
    @Bean("authTokenProperties")
    @ConfigurationProperties(prefix = "auth.token")
    @ConditionalOnProperty(value = "auth.token.enabled", havingValue = "true")
    @ConditionalOnMissingBean(name = "authTokenProperties")
    public AuthTokenProperties authTokenProperties(){
        return new AuthTokenProperties();
    }

    @Bean("authTokenManager")
    @ConditionalOnProperty(value = "auth.token.enabled", havingValue = "true")
    @ConditionalOnMissingBean(name = "ConditionalOnProperty")
    public AuthTokenManager authTokenManager(AuthTokenProperties authTokenProperties){
        return new AuthTokenManager(authTokenProperties);
    }

    @Bean
    @ConditionalOnBean(value = {AuthTokenManager.class, AuthTokenProperties.class})
    public AuthTokenFilter tokenAuthFilter(AuthTokenProperties authTokenProperties, AuthTokenManager authTokenManager){
        return new AuthTokenFilter(authTokenProperties, authTokenManager);
    }
    @Bean("tokenAuthFilterRegistrationBean")
    @ConditionalOnBean(AuthTokenFilter.class)
    @ConditionalOnMissingBean(name = "tokenAuthFilterRegistrationBean")
    public FilterRegistrationBean<AuthTokenFilter> tokenAuthFilterRegistrationBean(AuthTokenFilter authTokenFilter) {
        FilterRegistrationBean<AuthTokenFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(authTokenFilter);
        registrationBean.addUrlPatterns("/*");
        registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE+1);
        return registrationBean;
    }
}
